<?php
/**
 * Created by PhpStorm
 * User: 龍zero
 * Date: 2022-06-07
 * Time: 9:25
 */

namespace App\Middleware;


use Hyperf\Config\Annotation\Value;
use Hyperf\Context\Context;
use Hyperf\Contract\ContainerInterface;
use Hyperf\HttpMessage\Stream\SwooleFileStream;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class ResourceMiddleware implements MiddlewareInterface
{

    /**
     * @var ContainerInterface
     */
    protected $container;

    protected $direction = BASE_PATH . '/public';

    /**
     * @Value("file.include")
     */
    protected $fileInclude;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $path = $request->getUri()->getPath();
        if($ext = $this->getEndWith($path,$this->fileInclude)){
            if(is_file($this->direction.$path)){
                $response = Context::get(ResponseInterface::class)
                    ->withBody(new SwooleFileStream($this->direction . $path));
                $respMatchMime = [
                    'jpg' => $response->withAddedHeader('Content-Type','image/jpeg'),
                    'jpeg' => $response->withAddedHeader('Content-Type','image/jpeg'),
                    'png' => $response->withAddedHeader('Content-Type','image/png'),
                    'gif' => $response->withAddedHeader('Content-Type','image/gif'),
                    'xls' => $response->withAddedHeader('Content-Type','application/vnd.ms-excel'),
                    'xlsx' => $response->withAddedHeader('Content-Type','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'),
                    'doc' => $response->withAddedHeader('Content-Type','application/msword'),
                    'docx' => $response->withAddedHeader('Content-Type','application/vnd.openxmlformats-officedocument.wordprocessingml.document'),
                    'mp4' => $response->withAddedHeader('Content-Type','video/mp4'),
                    'avi' => $response->withAddedHeader('Content-Type','video/x-msvideo')
                ];

                return $respMatchMime[$ext];
            }
        }
        return  $handler->handle($request);
    }

    public function getEndWith($path,$extArr){
        $ext = substr($path,strrpos($path,'.')+1);
        if(in_array($ext,$extArr)){
            return $ext;
        }
        return '';
    }
}